package com.hzit.security.filter;

import com.alibaba.fastjson.JSON;
import com.hzit.security.entity.LoginUser;
import com.hzit.util.R;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.hzit.constant.CommonConstant.LOGIN_KEY_PREFIX;

/**
 * 功能：授权处理
 * 作者：WF
 */
public class HzitAuthenticationRightsFilter extends BasicAuthenticationFilter {

	private StringRedisTemplate redisTemplate;
	public HzitAuthenticationRightsFilter(AuthenticationManager authenticationManager,StringRedisTemplate redisTemplate) {
		super(authenticationManager);
		this.redisTemplate = redisTemplate;
	}
	//1. 授权处理逻辑
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
		//1.1 得到请求头
		String token = request.getHeader("token");
		//1.2 判断是否有值
		if(!StringUtils.hasText(token)){
			chain.doFilter(request,response);
			return;
		}
		//1.3 根据请求头得到redis中的登录用户LoginUser
		String key = LOGIN_KEY_PREFIX + token;
		String s = redisTemplate.opsForValue().get(key);
		LoginUser loginUser = JSON.parseObject(s, LoginUser.class);
		//1.4 构造认证成功的对象
		UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
		//1.5 如果授权成功,将此认证成功对象放到线程本地变量SecuritycontextHolder中
		if(upat != null){
			SecurityContextHolder.getContext().setAuthentication(upat);
		}else{
			R<Object> r = R.fail("授权失败！");
			ResponseUtil.writeStr(response,JSON.toJSONString(r));
		}
		//1.6 最后，放行过滤器
		chain.doFilter(request,response);
	}
}
